/* eslint-disable keyword-spacing,indent */
// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------

module.exports = class extends think.cmswing.admin {
  constructor(ctx) {
    super(ctx); // 调用父级的 constructor 方法，并把 ctx 传递进去
    // 其他额外的操作
    this.tactive = 'order';
  }
  /**
   * index action
   * @return {Promise} []
   */
  indexAction() {
    // auto render template file index_index.html

    return this.display();
  }
  // 订单列表
  async listAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    const data = await this.model('cmswing/order').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '订单管理-订单列表';
    return this.display();
  }
  // 订单列表导出
  async listexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    const data = await this.model('cmswing/order').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }

  async listreviewedAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.status = ['!=', 0];
    const data = await this.model('cmswing/order').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '订单复核-已复核';
    return this.display();
  }
  // 订单复核-已复核列表导出
  async listreviewedexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.status = ['!=', 0];
    const data = await this.model('cmswing/order').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }
  // 订单复核列表
  async listreviewAction() {
    const map = {
      status: 0
    };
    map.is_del = 0;
    const data = await this.model('cmswing/order').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使
    this.active = 'admin/order/listreview';
    this.assign('list', data.data);
    this.meta_title = '订单复核-未复核';
    return this.display();
  }
  // 问题订单
  async listproblemAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.problem_type = '问题订单';
    const data = await this.model('cmswing/order').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '问题订单';
    return this.display();
  }
  // 问题订单列表导出
  async listproblemexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.problem_type = '问题订单';
    const data = await this.model('cmswing/order').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }
  // 订单复核
  async reviewAction() {
    if (this.isPost) {
      const id = this.post('id');
      const admin_remark = this.post('admin_remark');
      const zuofeishijian = new Date().toLocaleString();
      const voids = await this.model('order').where({
        id: id
      }).update({
        status: 5,
        remark4: admin_remark,
        zuofeishijian: zuofeishijian
      });
      if (voids) {
        return this.success({
          name: '操作成功！',
          url: this.referer()
        });
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '订单复核';
      return this.display();
    }
  }
  /**
   * 审核订单达成
   */
  async accomplishAction() {
    if (this.isPost) {
      const id = this.post('id');
      const order = await this.model('order').where({
        id: id,
        status: 0
      }).find();
      if (think.isEmpty(order)) {
        return this.fail('操作失败！');
      }
      let resdata;
      let resp;
      if (order.yewuleixing == 0 || order.yewuleixing == 1) {
        // if (order.gongqueren == 0 || order.xuqueren == 0) {
        //   return this.fail('请等待业务员和客户确认订单后审核！');
        // }
        if (order.status != 0) {
          return this.fail('该订单已被处理无法审核！');
        }
        const memberdata = await this.model('member').where({
          id: order.gongid
        }).find();
        const memberdata2 = await this.model('member').where({
          id: order.xuid
        }).find();
        let action = '';
        if (memberdata.groupid == 12 && memberdata2.groupid != 12) {
          if (memberdata2.oastatus == 1) {
            return this.fail('该用户正在OA系统注册流程中，请等待流程审核完毕。');
          }
          const count = await this.requestOA('executeQuery', {
            sql: `select count(id) from uf_xskh6 where nsrsbh='${memberdata2.nsrsbh}'`
          });
          if (typeof (count) === 'undefined') {
            return this.fail('OA系统查询用户异常，请重试。');
          }
          memberdata2.yewuyuan = memberdata.ygbh;
          const gsmcid = await this.model('zzjg').where({
            zzjg: order.gong_gsmc
          }).getField('id', true);
          if (think.isEmpty(gsmcid)) {
            return this.fail('核心企业业务员公司名称有误，请先完善用户信息。');
          }
          memberdata2.company = gsmcid;
          if (JSON.stringify(count.data.list[0]).indexOf('0') != -1) {
            action = 'CustomerRegister';
            try {
              resp = await this.requestOA(action, memberdata2);
              if (typeof (resp) === 'undefined') {
                return this.fail('OA系统客户注册异常，请重试。');
              }
              if (resp.errno !== 0) { // 调用接口失败
                think.logger.error('OA系统客户注册失败:', action, memberdata2, resp);
                return this.fail('OA系统客户注册失败，请重试。');
              } else {
                const usertoorder = await this.model('usertoorder').add({
                  user_id: memberdata2.id,
                  order_id: order.id
                });
                resdata = resp;
                const memberres = await this.model('member').where({
                  id: order.xuid
                }).update({
                  oastatus: 1
                });
              }
            } catch (e) {
              think.logger.error('OA系统客户注册失败:', e);
              return this.fail('OA系统客户注册失败，请重试。');
            }
          } else {
            action = 'SaleOrder';
            order.user_info = memberdata2;
            try {
              resp = await this.requestOA(action, order);
              if (typeof (resp) === 'undefined') {
                return this.fail('OA系统生成销售合同异常，请重试。');
              }
              if (resp.errno !== 0) { // 调用接口失败
                think.logger.error('OA系统生成销售合同失败:', action, order, resp);
                return this.fail('OA系统生成销售合同失败，请重试。');
              } else {
                resdata = resp;
              }
            } catch (e) {
              think.logger.error('OA系统生成销售合同失败:', e);
              return this.fail('OA系统生成销售合同失败，请重试。');
            }
          }
        } else if (memberdata.groupid != 12 && memberdata2.groupid == 12) {
          if (memberdata.oastatus == 1) {
            return this.fail('该用户正在OA系统注册流程中，请等待流程审核完毕。');
          }
          const count = await this.requestOA('executeQuery', {
            sql: `select count(id) count from uf_test123 where nsrsbh='${memberdata.nsrsbh}'`
          });
          if (typeof (count) === 'undefined') {
            return this.fail('OA系统查询用户异常，请重试。');
          }
          memberdata.yewuyuan = memberdata2.ygbh;
          const gsmcid = await this.model('zzjg').where({
            zzjg: order.xu_gsmc
          }).getField('id', true);
          if (think.isEmpty(gsmcid)) {
            return this.fail('核心企业业务员公司名称有误，请先完善用户信息。');
          }
          memberdata.company = gsmcid;
          if (JSON.stringify(count.data.list[0]).indexOf('0') != -1) {
            action = 'SupplierRegister';
            try {
              resp = await this.requestOA(action, memberdata);
              if (typeof (resp) === 'undefined') {
                return this.fail('OA系统供应商注册异常，请重试。');
              }
              if (resp.errno !== 0) { // 调用接口失败
                think.logger.error('OA系统供应商注册失败', action, memberdata, resp);
                return this.fail('OA系统供应商注册失败，请重试。');
              } else {
                const usertoorder = await this.model('usertoorder').add({
                  user_id: memberdata.id,
                  order_id: order.id
                });
                resdata = resp;
                const memberres2 = await this.model('member').where({
                  id: order.xuid
                }).update({
                  oastatus: 1
                });
              }
            } catch (e) {
              think.logger.error('OA系统供应商注册失败:', e);
              return this.fail('OA系统供应商注册失败，请重试。');
            }
          } else {
            action = 'CaigouOrder';
            order.user_info = memberdata;
            try {
              resp = await this.requestOA(action, order);
              if (typeof (resp) === 'undefined') {
                return this.fail('OA系统生成采购合同异常，请重试。');
              }
              if (resp.errno !== 0) { // 调用接口失败
                think.logger.error('OA系统生成采购合同失败:', action, order, resp);
                return this.fail('OA系统生成采购合同失败，请重试。');
              } else {
                resdata = resp;
              }
            } catch (e) {
              think.logger.error('OA系统生成采购合同失败:', e);
              return this.fail('OA系统生成采购合同失败，请重试。');
            }
          }
        } else if (memberdata.groupid == 12 && memberdata2.groupid == 12) {
          return this.fail('同为环嘉不能做生意。');
        } else {
          return this.fail('销售双方关系存在问题。');
        }
      }
      const remarkData = this.post();
      const {
        remark_type
      } = remarkData;
      remarkData.status = 1;
      const {
        remarksId,
        updateData
      } = await this.addremark();
      const remarkKey = get_remark_key(remark_type);
      if (remarkKey) {
        updateData[remarkKey] = remarksId;
      }
      if (order.order_userid == order.xuid && order.gongqueren == 0) {
        updateData.gongqueren = 1;
      }
      if (order.order_userid == order.gongid && order.xuqueren == 0) {
        updateData.xuqueren = 1;
      }
      const audit = await this.model('order').where({
        id: id
      }).update(updateData);
      if (audit) {
        return this.success({
          name: '操作成功！',
          url: this.referer()
        });
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '订单复核';
      return this.display();
    }
  }

  /**
   * 作废订单
   */
  async terminationAction() {
    if (this.isPost) {
      const remarkData = this.post();
      const {
        id,
        remark_type
      } = remarkData;
      const orderInfo = await this.model('order').where({
        id: id,
        status: 0
      }).find();
      if (think.isEmpty(orderInfo)) {
        return this.fail('操作失败！');
      }
      remarkData.status = 4;
      const {
        remarksId,
        updateData
      } = await this.addremark();
      const remarkKey = get_remark_key(remark_type);
      if (remarkKey) {
        updateData[remarkKey] = remarksId;
      }
      if (!think.isEmpty(remarksId)) {
        if (orderInfo.order_userid == orderInfo.xuid && orderInfo.gongqueren == 0) {
          updateData.gongqueren = 2;
        }
        if (orderInfo.order_userid == orderInfo.gongid && orderInfo.xuqueren == 0) {
          updateData.xuqueren = 2;
        }
        updateData.decision_problem_node = get_pathname(this.referer());
        updateData.decision_problem_time = remarkData.remark_time;
        updateData.decision_problem_userid = remarkData.remark_name;
        const voids = await this.model('order').where({
          id: id
        }).update(updateData);
        if (voids) {
          this.success({
            name: '操作成功！',
            url: this.referer()
          });
          if (orderInfo.gongxufabuid) {
            this.ctx.request.body = {
              post: {
                id: orderInfo.gongxufabuid,
                operation: '上架',
                remark_type: this.active,
                remark_contents: '订单终止后自动上架'
              }
            };
            await this.action('admin/gongxufabu', 'sale');
          }
        } else {
          return this.fail('操作失败！');
        }
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      const order = await this.model('cmswing/order').where({
        id: id
      }).find();
      this.assign('order', order);
      this.meta_title = '订单复核';
      return this.display();
    }
  }
  async remarksAction() {
    if (this.isPost) {
      const remarkData = this.post();
      const {
        id,
        remark_type
      } = remarkData;
      const orderInfo = await this.model('order').where({
        id: id,
        status: 4
      }).find();
      if (think.isEmpty(orderInfo)) {
        return this.fail('操作失败！');
      }
      const {
        remarksId
      } = await this.addremark();
      if (!think.isEmpty(remarksId)) {
        return this.success({
          name: '操作成功！',
          url: this.referer()
        });
      }else{
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '订单备注';
      return this.display();
    }
  }
  async viewremarksAction() {
    if (this.isPost) {

    } else {
      const {
        id,
        model_name = null
      } = this.get();
      const remarks = await this.model('cmswing/remarks').where({
        foreign_key: id,
        model_name: model_name
      }).select();
      this.assign('remarks', remarks);
      this.meta_title = '订单备注';
      return this.display();
    }
  }
  /**
   * 完结订单
   */
  async finishAction() {
    if (this.isPost) {
      const id = this.post('id');
      const admin_remark = this.post('admin_remark');
      const wanchengshijian = new Date().toLocaleString();
      const finish = await this.model('order').where({
        id: id
      }).update({
        status: 3,
        remark3: admin_remark,
        wanchengshijian: wanchengshijian
      });
      if (finish) {
        return this.success({
          name: '操作成功！',
          url: this.referer()
        });
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '完结订单';
      return this.display();
    }
  }

  /**
   * 问题订单备注
   */
  async remarkAction() {
    if (this.isPost) {
      const id = this.post('id');
      const admin_remark = this.post('admin_remark');
      const remark = await this.model('order').where({
        id: id
      }).update({
        remark5: admin_remark
      });
      if (remark) {
        return this.success({
          name: '操作成功！',
          url: this.referer()
        });
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '备注订单';
      return this.display();
    }
  }
  /**
   * 查看订单
   * @returns {*}
   */
  async seeAction() {
    const id = this.get('id');
    this.meta_title = '查看订单';
    // 获取订单信息
    const order = await this.model('cmswing/order').find(id);
    // 购买人信息
    const user = await this.model('member').find(order.gongid);
    const user2 = await this.model('member').find(order.xuid);
    this.assign('user', user);
    this.assign('user2', user2);
    this.assign('order', order);
    return this.display();
  }

  /**
   * 查看订单
   */
  vieworderAction() {
    const list = [1, 2, 3];
    this.assign('list', list);
    return this.display();
  }

  /**
   * 收款单
   */

  async receivingAction() {
    const data = await this.model('doc_receiving').page(this.get('page')).order('create_time DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    // console.log(data.data);
    // this.active="admin/order/list"
    for (const val of data.data) {
      switch (val.payment_id) {
        case 100:
          val.channel = '预付款支付';
          break;
        case 1001:
          val.channel = '货到付款';
          break;
        default:
          val.channel = await this.model('pingxx').where({
            id: val.payment_id
          }).getField('title', true);
      }
      val.order_id = await this.model('order').where({
        id: val.order_id
      }).getField('order_no', true);
    }
    this.assign('list', data.data);
    // this.active="admin/order/receiving"
    this.meta_title = '收款单';
    return this.display();
  }

  /**
   * 退款单
   */

  refundAction() {
    this.active = 'admin/order/receiving';
    this.meta_title = '退款单';
    return this.display();
  }

  /*  async order2oa(id){
      let resdata;
      const order = await this.model('order').where({id: id}).find();
      let memberdata = await this.model('member').where({id:order.gongid}).find();
      let memberdata2 = await this.model('member').where({id:order.xuid}).find();
      let action = '';
      if (memberdata.groupid ==12&&memberdata2.status !=12) {
        const resp = await this.requestOA('executeQuery', { sql: 'select * from hrmsubcompany where nvl(canceled,0)<>1 order by id' });
        console.log('resp='+resp);
        const count = await this.requestOA('executeQuery', { sql: `select count(id) from uf_xskh6 where nassbh='${memberdata2.user_code}'` });
        if (count==0) {
          action = 'CustomerRegister';
          memberdata2.yewuyuan = memberdata.ygbh;
          memberdata2.company = order.gong_gsmc;
          try {
            const resp = await this.requestOA(action, memberdata2);
            if (resp.errno !== 0) {//调用接口失败
              return this.fail(resp.errmsg + '[WS]');
            }
          } catch (e) {
            return this.fail('注册失败，请重试。[WS]');
          }
        } else {
          action = 'SaleOrder';
          try {
            const resp = await this.requestOA(action, order);
            if (resp.errno !== 0) {//调用接口失败
              await this.model('order').where({id: id}).update({status: 0, remark1: null});//取消审核
              return this.fail(resp.errmsg + '[WS]');
            }
          } catch (e) {
            await this.model('order').where({id: id}).update({status: 0, remark1: null});//取消审核
            return this.fail('注册失败，请重试。[WS]');
          }
        }

      } else if (memberdata.status !=12&&memberdata2.status ==12) {
        const count = await this.requestOA('executeQuery', { sql: `select count(id) from uf_test123 where nsrsbh='${memberdata.user_code}'` });
        if (count==0) {
          action = 'SupplierRegister';
          memberdata.yewuyuan = memberdata2.ygbh;
          memberdata.company = order.xu_gsmc;
          try {
            const resp = await this.requestOA(action, memberdata);
            if (resp.errno !== 0) {//调用接口失败
              return this.fail(resp.errmsg + '[WS]');
            }
          } catch (e) {
            return this.fail('注册失败，请重试。[WS]');
          }
        } else {
          action = 'CaigouOrder';
          try {
            const resp = await this.requestOA(action, order);
            if (resp.errno !== 0) {//调用接口失败
              await this.model('order').where({id: id}).update({status: 0, remark1: null});//取消审核
              return this.fail(resp.errmsg + '[WS]');
            }
          } catch (e) {
            await this.model('order').where({id: id}).update({status: 0, remark1: null});//取消审核
            return this.fail('注册失败，请重试。[WS]');
          }
        }

      } else if (memberdata.status ==12&&memberdata2.status ==12) {
        await this.model('order').where({id: id}).update({status: 0, remark1: null});//取消审核
        return this.fail('同为环嘉不能做生意');
      } else {
        await this.model('order').where({id: id}).update({status: 0, remark1: null});//取消审核
        return this.fail('销售双方关系存在问题');
      }
      return this.success({name: '审核成功！', url: this.referer()});
    } */
};
